package cn.uniquesoft.controller;

import cn.uniquesoft.manager.Client;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.service.IRoleService;
import cn.uniquesoft.util.BrowserUtils;
import cn.uniquesoft.util.ContextUtil;
import cn.uniquesoft.util.IpUtil;
import cn.uniquesoft.vo.RoleVO;
import cn.uniquesoft.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;

/**
 * @创建人名 zjn
 * @创建日期 2017年9月3日 下午10:05:17
 * @文件描述 项目主目录
 */
@Controller
@RequestMapping(value = "/main")
public class MainController {
	@Autowired
	private IRoleService roleService;
	@RequestMapping(value = "/index")
	public ModelAndView index(HttpServletRequest request) {
		try {
			UserVO userVO = ClientManager.getInstance().getClient().getUser();
			HashMap<String, Object> model = new HashMap<String, Object>();
			if (null != userVO) {
				model.put("user", userVO);
				addSession(userVO, request);

				RoleVO role = new RoleVO();
				role.setCrolename(userVO.getCroleeng());
				role = this.roleService.findOne(role);
				model.put("role", role);
				// 根据用户角色管理菜单显示

//				model.put("menus", MenuUtil.getNavMenuList((List<MenuVO>) this.menuService.getItemsByIds(roles.getMenuids())));
				//model.put("menus", MenuUtil.getNavMenuList((List<MenuVO>) this.menuService.getItems(null)));
//				model.put("menus", MenuUtil.getMenuJson((List<MenuVO>) this.menuService.getItemsByIds(roles.getMenuids())));
				return new ModelAndView("/mgr/main/index", model);
			}else{
				return new ModelAndView("/mgr/login/index");
			}
		} catch (Exception e) {
			return new ModelAndView("/mgr/login/index");
		}
	}
	// 添加用户到session中,统计在线用户
	private void addSession(UserVO userVO, HttpServletRequest req) {
		// 统计在线用户
		try {
			// 添加user信息到session中
			HttpSession session = ContextUtil.getSession();
			Client client = new Client();
			client.setAdddate(new Date());
			client.setCip(IpUtil.getIpAddr(req));
			client.setUser(userVO);
			client.setCbrowser(BrowserUtils.checkBrowse(req));
			ClientManager.getInstance().addClient(session.getId(), client);
		} catch (Exception e) {
			System.out.println("用户在线人数统计，异常！");
			e.printStackTrace();
		}
	}
}
